package com.zhanhong.opencvdemo.loader;

import android.content.Context;
import android.graphics.Color;

import com.wang.avi.AVLoadingIndicatorView;
import com.wang.avi.Indicator;

import java.util.WeakHashMap;

public final class LoaderCreator {

    private static final WeakHashMap<String, Indicator> INDICATOR_MAP = new WeakHashMap<>();

    public static AVLoadingIndicatorView create(Context context, Enum<LoaderStyle> style) {
        AVLoadingIndicatorView avLoadingIndicatorView = new AVLoadingIndicatorView(context);
        if (INDICATOR_MAP.get(style.name()) == null) {
            Indicator indicator = getIndicator(style);
            if (indicator != null) {
                INDICATOR_MAP.put(style.name(), indicator);
            }
        }
        avLoadingIndicatorView.setIndicator(INDICATOR_MAP.get(style.name()));
        avLoadingIndicatorView.setIndicatorColor(Color.parseColor("#63B8FF"));
        return avLoadingIndicatorView;
    }

    private static Indicator getIndicator(Enum<LoaderStyle> style) {

        final StringBuilder sbStyleName = new StringBuilder();
        final String styleName = style.name();
        try {
            if (!styleName.contains(".")) {
                final String packageName = AVLoadingIndicatorView.class.getPackage().getName();
                sbStyleName.append(packageName).append(".indicators").append(".");
            }
            sbStyleName.append(styleName);
            Class<?> drawableClass = Class.forName(sbStyleName.toString());
            return (Indicator) drawableClass.newInstance();
        } catch (Exception e) {
            e.printStackTrace();
            return null;
        }

    }

}
